﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Input;
using SilentWebsite.Model;
using SilentWebsite.Model.Contracts;
using SilentWebsite.ViewModels.Commands;
using SilentWebsite.Web;
using Telerik.Windows;
using Telerik.Windows.Controls;

namespace SilentWebsite.ViewModels
{
    public class DesignViewModel : DynamicControlManager
    {
        public ICommand SaveCommand { get; set; }

        public ICollection<DynamicControl> DynamicControls { get; set; }
        public Project CurrentProjectPage { get; set; }

        public DesignViewModel(Panel layoutRoot, RadContextMenu menu) : base(layoutRoot, menu)
        {
            SaveCommand = new SimpleCommand(() =>
                {
                    //CurrentProjectPage.Markup = SaveLayout();
                    SilentEngine.Instance.Data.UpdateProject(CurrentProjectPage);
                });

            DynamicControls = new ObservableCollection<DynamicControl>();
            SilentEngine.Instance.Data.Completed += DataOnCompleted;
            SilentEngine.Instance.Data.GetControls();
            //SilentEngine.Instance.Data.GetProjects(SilentEngine.Instance.CurrentUser.Id);
            designMenu.ItemClick += MenuBaseItemClick;
        }

        private void DataOnCompleted(object sender, ActionEventArg e)
        {
            if (e.Result is ICollection<DynamicControl>)
            {
                var collection = e.Result as ICollection<DynamicControl>;
                DynamicControlFactory.DynamicControls = collection;
                var addButton = (RadMenuItem)designMenu.Items[0];
                collection.ToList().ForEach(x =>
                    {
                        DynamicControls.Add(x);
                        addButton.Items.Add(x.Name);
                    }
                );
            }
            else if (e.Result is ICollection<ProjectPage>)
            {
                var projects = e.Result as ICollection<ProjectPage>;
                //CurrentProjectPage = projects.FirstOrDefault();
            }
        }
        private void MenuBaseItemClick(object sender, RadRoutedEventArgs e)
        {
            var clickedItem = e.OriginalSource as RadMenuItem;
            if (clickedItem != null)
                MenuItemClickExecute(clickedItem.Header.ToString());
        }
        private void MenuItemClickExecute(string name)
        {
            switch (name)
            {
                case "Delete":
                    RemoveElement(LastSelectedElement);
                    break;
                default:
                    AddElement(DynamicControlFactory.Create(name));
                    break;
            }
        }
    }
}
